<template>
  <el-dialog
    v-model="visible"
    :title="$t('product.chooseSupplier')"
    :modal="false"
    top="100px"
    :close-on-click-modal="false"
    width="914px"
    class="component-supplier-select supplier-select-dialog"
  >
    <!-- native modifier has been removed, please confirm whether the function has been affected  -->
    <el-form
      :inline="true"
      :model="dataForm"
      class="demo-form-inline"

      @submit.prevent
    >
      <el-form-item :label="$t('shop.supplierName')">
        <el-input
          v-model="supplierName"
          :placeholder="$t('shop.supplierName')"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <div
          class="default-btn primary-btn"
          @click="searchProd"
        >
          {{ $t("order.query") }}
        </div>
      </el-form-item>
      <el-form-item>
        <div
          class="default-btn"
          @click="clean"
        >
          {{ $t("shop.resetMap") }}
        </div>
      </el-form-item>
    </el-form>

    <div class="table-con supplier-list-con">
      <el-table
        ref="prodTableRef"
        v-loading="dataListLoading"
        :data="dataList"
        header-cell-class-name="table-header"
        row-class-name="supplier-table-row"
        style="width: 100%;"
        max-height="366"
      >
        <el-table-column
          v-if="isSingle"
          width="50"
          align="left"
        >
          <template #default="scope">
            <div>
              <!-- native modifier has been removed, please confirm whether the function has been affected  -->
              <el-radio
                v-model="singleSelectSupplierId"
                :label="scope.row.supplierId"
                @change="getSelectProdRow(scope.row)"
              >
&nbsp;
              </el-radio>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="!isSingle"
          type="selection"
          align="left"
          width="50"
        />
        <el-table-column
          prop="supplierName"
          align="left"
          :label="$t('shop.supplierName')"
          width="230"
        />
        <el-table-column
          prop="tel"
          align="left"
          :label="$t('shop.tel')"
          width="180"
        >
          <template #default="scope">
            <span>{{ scope.row.tel || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="contactName"
          align="left"
          :label="$t('shop.contactName')"
          width="160"
        >
          <template #default="scope">
            <span>{{ scope.row.contactName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="contactTel"
          align="left"
          :label="$t('shop.contactTel')"
          width="160"
        >
          <template #default="scope">
            <span>{{ scope.row.contactTel || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="left"
          :label="$t('product.status')"
        >
          <template #default="scope">
            <span
              v-if="scope.row.status === 1"
              class="tag-text"
            >{{ $t("groups.startUsing") }}</span>
            <span
              v-if="scope.row.status === 0"
              class="tag-text"
            >{{ $t("publics.disable") }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
    />
    <template #footer>
      <div
        class="default-btn"
        @click="visible = false"
      >
        {{ $t("crud.filter.cancelBtn") }}
      </div>
      <div
        class="default-btn primary-btn"
        @click="submitProds()"
      >
        {{ $t("crud.filter.submitBtn") }}
      </div>
    </template>
  </el-dialog>
</template>

<script setup>

const emit = defineEmits(['refreshSelectSupplier'])
const props = defineProps({
  isSingle: {
    default: false,
    type: Boolean
  },
  dataUrl: {
    default: '/supplier/supplier/page',
    type: String
  }
})

const visible = ref(false)
const dataForm = reactive({
  supplier: ''
})
const singleSelectSupplierId = ref(0)
let selectProds = []
const dataList = ref([])
const supplierName = ref('')
let shopCategoryId = null
const pageIndex = ref(1)
const pageSize = ref(10)
const totalPage = ref(0)
const dataListLoading = ref(false)
let dataListSelections = []

onActivated(() => {
  getDataList()
})

// 获取数据列表
const prodTableRef = ref(null)
const init = (_selectProds) => {
  singleSelectSupplierId.value = 0
  selectProds = _selectProds
  visible.value = true
  dataListLoading.value = true
  if (selectProds) {
    selectProds.forEach(row => {
      dataListSelections.push(row)
    })
  }
  getDataList()
}
const getDataList = () => {
  http({
    url: http.adornUrl(props.dataUrl),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageIndex.value,
          size: pageSize.value,
          supplierName: supplierName.value || null,
          status: 1
        }
      )
    )
  }).then(({ data }) => {
    dataList.value = data.records
    totalPage.value = data.total
    testSuppliers()
    dataListLoading.value = false
    if (selectProds) {
      nextTick(() => {
        selectProds.forEach(row => {
          const index = dataList.value.findIndex((prodItem) => prodItem.supplierId === row.supplierId)
          if (index !== -1)prodTableRef.value?.toggleRowSelection(dataList.value[index])
        })
      })
    }
  })
}
defineExpose({ init })
// 去除处于禁用状态的的供应商
const testSuppliers = () => {
  const suppliersTest = dataList.value
  let supplierNum = totalPage.value
  // for ()
  for (let i = 0; i < suppliersTest.length; i++) {
    if (suppliersTest[i].status === 0) {
      suppliersTest.splice(i, 1)
      supplierNum = supplierNum - 1
    }
  }
  totalPage.value = supplierNum
  dataList.value = suppliersTest
}
// 每页数
const sizeChangeHandle = (val) => {
  pageSize.value = val
  pageIndex.value = 1
  getDataList()
}
// 当前页
const currentChangeHandle = (val) => {
  pageIndex.value = val
  getDataList()
}
// 单选商品事件
const getSelectProdRow = (row) => {
  dataListSelections = [row]
}
// 多选点击事件
const selectChangeHandle = (selection) => {
  dataList.value.forEach((tableItem) => {
    const selectedProdIndex = selection.findIndex((selectedProd) => {
      if (!selectedProd) {
        return false
      }
      return selectedProd.supplierId === tableItem.supplierId
    })
    const dataSelectedProdIndex = dataListSelections.findIndex((dataSelectedProd) => dataSelectedProd.supplierId === tableItem.supplierId)
    if (selectedProdIndex > -1 && dataSelectedProdIndex === -1) {
      dataListSelections.push(tableItem)
    } else if (selectedProdIndex === -1 && dataSelectedProdIndex > -1) {
      dataListSelections.splice(dataSelectedProdIndex, 1)
    }
  })
}
/**
 * 获取分类id
 */
const handleChange = (val) => {
  shopCategoryId = val[val.length - 1]
}
/**
 * 根据条件搜索商品
 */
const searchProd = () => {
  pageIndex.value = 1
  getDataList()
}
/**
 * 清空搜索条件
 */
const clean = () => {
  supplierName.value = ''
  shopCategoryId = null
}
// 确定事件
const submitProds = () => {
  const suppliers = []
  dataListSelections.forEach(item => {
    const supplierIndex = suppliers.findIndex((supplier) => supplier.supplierId === item.supplierId)
    if (supplierIndex === -1) {
      suppliers.push(
        {
          supplierId: item.supplierId,
          supplierName: item.supplierName,
          isDefault: item.isDefault
        }
      )
    }
  })
  emit('refreshSelectSupplier', suppliers)
  dataListSelections = []
  selectProds = []
  visible.value = false
}

</script>
<style lang="scss" scoped>
.component-supplier-select.supplier-select-dialog {
  .supplier-list-con {
    margin-bottom: 20px;
    :deep(.supplier-table-row) {
      height: 55px;
    }
  }
}

</style>
